package com.zking.ssm.aspect;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zking.ssm.util.PageBean;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author小李飞刀
 * @site www.javaxl.com
 * @company xxx公司
 * @create  2022-08-12 16:32
 */
@Component
@Aspect
public class PagerAspect {

    /**
     * *：返回值类型
     * *..：无限包
     * *Service：以Service结尾接口名
     * *Pager：以Pager方法
     * 只要同时匹配上诉四个条件，就会被列为目标对象
     * 上述配置要生效，代理注解<aop:aspectj-autoproxy/>不能少
     * @param args
     * @return
     * @throws Throwable
     */
    @Around("execution(* *..*Biz.*Pager(..))")
    public Object invoke(ProceedingJoinPoint args) throws Throwable {
        Object[] params = args.getArgs();
        PageBean pageBean = null;
        for (Object param : params) {
            if(param instanceof PageBean){
                pageBean = (PageBean)param;
                break;
            }
        }

        if(pageBean != null && pageBean.isPagination())
            PageHelper.startPage(pageBean.getPage(),pageBean.getRows());

//        执行目标方法
        Object list = args.proceed(params);

        if(null != pageBean && pageBean.isPagination()){
            PageInfo pageInfo = new PageInfo((List) list);
            pageBean.setTotal(pageInfo.getTotal()+"");
        }
        return list;
    }


}
